package site.wtcc.originalfavor.func.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

/**
 * json工具
 * jackson的ObjectMapper实例化是一个性能瓶颈，如果提前准备好实例会比fastJson要快一倍左右，
 * 随后我打开ObjectMapper构造方法看了下，确实比较繁琐，因此在实际应用中我们转json字符串的时候应当使用同一个ObjectMapper实例，
 * 避免每次手动去new新的实例，
 * 而FastJson是用静态方法（JSONObject.toJSONString()）因此我们在常规使用的时候不方便像jsckson那样把实例提前准备好。
 *
 * @author hexiaodou
 * @date 2022/11/07 15:11:08
 */
@Slf4j
public class JsonUtils {

    private static final ObjectMapper mapper;

    static {
        mapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        mapper.registerModule(javaTimeModule);
        SimpleModule module = new SimpleModule();
        mapper.registerModule(module);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
    }

    public static <T> Optional<String> toJson(T obj) {
        try {
            return Optional.of(mapper.writeValueAsString(obj));
        } catch (Exception ex) {
            return Optional.empty();
        }
    }

    public static <T> String toJson(T obj, String defaultValue) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (Exception ex) {
            return defaultValue;
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> Optional<T> fromJson(String json, Class<T> tClass) {
        try {
            if (tClass == String.class) {
                return Optional.of((T) json);
            }
            return Optional.of(mapper.readValue(json, tClass));
        } catch (Exception ex) {
            return Optional.empty();
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T fromJson(String json, Class<T> tClass, T defaultValue) {
        try {
            if (tClass == String.class) {
                return (T) json;
            }
            return mapper.readValue(json, tClass);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            return defaultValue;
        }
    }

    public static <T> T read(JsonNode json, Class<T> tClass) {
        if (json == null || json.isNull()) {
            return null;
        }
        return fromJson(json.asText(), tClass, null);
    }

    public static <T> T readFromJson(String mailInfoList, TypeReference<T> typeReference) {
        try {
            return mapper.readValue(mailInfoList, typeReference);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
        return null;
    }

    public static <T> T readFromJson(String mailInfoList, TypeReference<T> typeReference, T defaultValue) {
        try {
            return mapper.readValue(mailInfoList, typeReference);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
        return defaultValue;
    }
}
